package com.example.demo.service.exam.impl;

import com.example.demo.domain.CombineClause;
import com.example.demo.domain.SingleClause;
import com.example.demo.domain.exam.ExamUserDelay;
import com.example.demo.exception.ExceptionUtils;
import com.example.demo.mapper.ExamUserDelayMapper;
import com.example.demo.service.exam.ExamUserDelayService;
import com.example.demo.service.impl.BaseServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class ExamUserDelayServiceImpl extends BaseServiceImpl<ExamUserDelayMapper, ExamUserDelay> implements ExamUserDelayService {

    private final ExamUserDelayMapper mapper;

    @Override
    public void insert(ExamUserDelay entity) {
        valid(entity);
        mapper.insert(entity);
    }

    @Override
    public ExamUserDelay getByExamUserId(Long examId, Long userId) {
        if (userId == null) {
            throw ExceptionUtils.exception("用户标识不能为空");
        }
        if (examId == null) {
            throw ExceptionUtils.exception("考试标识不能为空");
        }
        return super.selectOne(CombineClause.and(
                SingleClause.equal("exam_id", examId),
                SingleClause.equal("user_id", userId)
        ));
    }

    @Override
    public void update(ExamUserDelay entity) {
        if (entity.getId() == null) {
            throw ExceptionUtils.exception("更新时主键标识能为空");
        }
        mapper.updateById(entity);
    }

    @Override
    public void delete(Long id) {
        if (id == null) {
            throw ExceptionUtils.exception("删除时主键标识能为空");
        }
        mapper.deleteById(id);
    }

    private void valid(ExamUserDelay entity) {
        Long userId = entity.getUserId();
        Long examId = entity.getExamId();
        Integer delayTime = entity.getDelayTime();
        if (userId == null) {
            throw ExceptionUtils.exception("用户标识不能为空");
        }
        if (examId == null) {
            throw ExceptionUtils.exception("考试标识不能为空");
        }
        if (delayTime == null || delayTime < 0) {
            throw ExceptionUtils.exception("延长时间不合理");
        }
        Optional.ofNullable(this.getByExamUserId(entity.getExamId(), entity.getUserId()))
                .ifPresent(value -> {
                    throw ExceptionUtils.exception("已经为该用户该场考试进行延时");
                });

    }

}
